import 'dart:isolate';
import 'dart:math';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/common/widget/gradient_button.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/shared_preferences_utils.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/core/utils/wifi/wifi_utils.dart';

import 'package:casdon/modules/device/application/notification/tuya_pair_net_guid_notifier.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';
import 'package:tuya_home_sdk_flutter/src/models/lead_model.dart';

final checkboxStateProvider = StateProvider.autoDispose<bool>((ref) => false);
final _stepIndexProvider = StateProvider.autoDispose<int>((ref) => 0);

@RoutePage()
class TuyaPairnetGuidScreen extends ConsumerWidget {
  final String pid;
  final String deviceName;

  const TuyaPairnetGuidScreen({
    required this.pid,
    required this.deviceName,
    super.key,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    ref.read(tuyaPairNetGuidNotifierProvider.notifier).setPid(pid);
    final state = ref.watch(tuyaPairNetGuidNotifierProvider);

    final isChecked = ref.watch(checkboxStateProvider);
    final checkboxNotifier = ref.read(checkboxStateProvider.notifier);

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CommonAppBar(title: '添加设备'),
      body: SafeArea(
        // 添加SafeArea包裹整个内容
        bottom: true, // 确保底部安全区域
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      SizedBox(height: 20.h),
                      state.when(
                        initial: () => const SizedBox.shrink(),
                        loading: () =>
                            const Center(child: CommonLoadingWidget()),
                        success: (model) => _buildDataView(model, context, ref),
                        failure: (error, statusCode) => Center(child: Text('')),
                      ),
                    ],
                  ),
                ),
              ),
            ),

            // 底部按钮与勾选
            state.when(
              initial: () => const SizedBox.shrink(),
              loading: () => const SizedBox.shrink(),
              failure: (_, __) => const SizedBox.shrink(),
              success: (model) {
                final leads = _getBtLeads(model);
                final helpUrl = model.display?.btHelpUrl;
                final singleLead = _getBtSingleLead(model);
                final bool showRadio = singleLead?.radioFlag ?? true;
                final String radioText = singleLead?.addBtText ?? "已按提示操作";
                final bool isQrFlow = _isQrFlow(model);
                final index = ref.watch(_stepIndexProvider);
                final current = (index >= 0 && index < leads.length)
                    ? leads[index]
                    : null;
                final shouldRequireCheck =
                    max(leads.length - 1, 0) == index && showRadio;
                final bool showScanButton =
                    isQrFlow && leads.isNotEmpty && index == leads.length - 1;
                return Padding(
                  padding: EdgeInsets.only(
                    left: 16.w,
                    right: 16.w,
                    bottom: 8.h,
                  ),
                  child: Column(
                    children: [
                      if (shouldRequireCheck)
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Checkbox(
                              value: isChecked,
                              onChanged: (value) {
                                checkboxNotifier.state = value ?? false;
                              },
                            ),
                            Text(
                              radioText,
                              style: context.textTheme.bodyMedium?.copyWith(
                                color:
                                    context.customColorThemeNonNull.textColor3,
                              ),
                            ),
                          ],
                        ),
                      SizedBox(height: 8.h),
                      Row(
                        children: [
                          if (index > 0)
                            Expanded(
                              child: OutlinedButton(
                                onPressed: () {
                                  final v = ref.read(
                                    _stepIndexProvider.notifier,
                                  );
                                  v.state = (index - 1).clamp(
                                    0,
                                    leads.length - 1,
                                  );
                                },
                                style: OutlinedButton.styleFrom(
                                  side: BorderSide(
                                    color: context.colorScheme.primary,
                                  ),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(24),
                                  ),
                                ),
                                child: const Text('上一步'),
                              ),
                            ),
                          if (index > 0) SizedBox(width: 12.w),
                          Expanded(
                            child: GradientButton(
                              text: showScanButton ? '扫描二维码' : '下一步',
                              textStyle: context.textTheme.labelLarge?.copyWith(
                                color: Colors.white,
                              ),
                              borderRadius: 24,
                              enabled:
                                  !shouldRequireCheck ||
                                  (shouldRequireCheck && isChecked == true),
                              onPressed:
                                  (!shouldRequireCheck ||
                                      (shouldRequireCheck && isChecked == true))
                                  ? () async {
                                      if (index < leads.length - 1) {
                                        ref
                                                .read(
                                                  _stepIndexProvider.notifier,
                                                )
                                                .state =
                                            index + 1;
                                      } else {
                                        if (showScanButton) {
                                          QRScannerRoute().push(context);
                                          return;
                                        } else {
                                          _goNextPage(context, ref);
                                        }
                                      }
                                    }
                                  : null,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 28.h),
                      if (helpUrl != null)
                        TextButton(
                          onPressed: () => {_goHelpWebPage(context, helpUrl)},
                          child: Text(
                            '联网提醒',
                            style: context.textTheme.bodyMedium?.copyWith(
                              color: context.colorScheme.primary,
                            ),
                          ),
                        ),
                    ],
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  List<dynamic> _getBtLeads(ThingSmartDeviceCategoryModel model) {
    try {
      final modes = model.linkModes;
      if (modes != null && modes.isNotEmpty) {
        dynamic qrMode;
        dynamic btMode;

        for (final mode in modes) {
          if (mode.linkMode == 10 && qrMode == null) {
            qrMode = mode;
          } else if (mode.linkMode == 7 && btMode == null) {
            btMode = mode;
          }
        }

        // 二维码配网时，文案和图片写死
        if (qrMode != null) {
          final overwriteLead = ThingSmartALeadModel(
            title:
                "添加设备\n第一步：进入机器的【设置】\n第二步：打开【网络设置】，连接WIFI\n第三步：扫描【设备绑定】内的二维码",
            iconUrl: "https://i.ibb.co/p63SV6Rp/869-3x.png",

            addBtText: null,
          );

          return [overwriteLead];
        }

        if (btMode != null && btMode.leadList != null) {
          return List<dynamic>.from(btMode.leadList!);
        }
      }
    } catch (_) {}
    return const [];
  }

  dynamic _getBtSingleLead(ThingSmartDeviceCategoryModel model) {
    Log.i("119615");
    try {
      final modes = model.linkModes;
      if (modes != null && modes.isNotEmpty) {
        dynamic m10;
        dynamic m7;
        for (final mode in modes) {
          if (mode.linkMode == 10 && m10 == null) {
            m10 = mode;
          } else if (mode.linkMode == 7 && m7 == null) {
            m7 = mode;
          }
        }

        if (m10 != null && m10.singleLead != null) {
          final overwriteLead = ThingSmartALeadModel(
            addBtText: null,
            radioFlag: true,
          );

          return overwriteLead;
        }
        return m7?.singleLead;
      }
    } catch (_) {}
    return null;
  }

  bool _isQrFlow(ThingSmartDeviceCategoryModel model) {
    try {
      final modes = model.linkModes;
      if (modes != null && modes.isNotEmpty) {
        for (final mode in modes) {
          if (mode.linkMode == 10) {
            return true;
          }
        }
      }
    } catch (_) {}
    return false;
  }

  String? _btIconUrl(ThingSmartDeviceCategoryModel model) {
    try {
      final modes = model.linkModes;
      if (modes != null && modes.isNotEmpty) {
        dynamic m7;
        for (final m in modes) {
          if (m.linkMode == 7) {
            m7 = m;
            break;
          }
        }
        final firstLead =
            (m7 != null && m7.leadList != null && m7.leadList.isNotEmpty)
            ? m7.leadList.first
            : null;
        final url = firstLead?.iconUrl;
        if (url != null && url.trim().isNotEmpty) return url;
      }
    } catch (_) {}
    return model.display?.btTipIconUrl;
  }

  Widget _buildDataView(
    ThingSmartDeviceCategoryModel model,
    BuildContext context,
    WidgetRef ref,
  ) {
    // 取 linkModes 中 linkMode == 7 的第一个 leadList 元素，用其 iconUrl；
    // 若不可用，退回 display.btTipIconUrl
    final leads = _getBtLeads(model);
    final index = ref.watch(_stepIndexProvider);
    final current = (index >= 0 && index < leads.length) ? leads[index] : null;
    final String? btIconUrl =
        (current != null &&
            (current.iconUrl is String) &&
            (current.iconUrl as String).trim().isNotEmpty)
        ? current.iconUrl as String
        : _btIconUrl(model);
    return Column(
      // 移除了Expanded和SingleChildScrollView
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        if (btIconUrl != null && btIconUrl.trim().isNotEmpty)
          Image.network(btIconUrl),
        SizedBox(height: 15.h),
        // 步骤指示器
        if (leads.length == 0)
          Text(
            model.display?.btTip ?? "",
            style: context.textTheme.bodyMedium?.copyWith(
              color: context.customColorThemeNonNull.textColor1,
            ),
          ),
        if (leads.length > 1)
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(leads.length, (i) {
              final selected = i == index;
              return Container(
                margin: EdgeInsets.symmetric(horizontal: 6.w),
                width: 22.w,
                height: 22.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: selected
                      ? const Color(0xFF666666)
                      : const Color(0xFFE0E0E0),
                  shape: BoxShape.circle,
                ),
                child: Text(
                  '${i + 1}',
                  style: context.textTheme.bodyMedium?.copyWith(
                    color: selected
                        ? Colors.white
                        : context.customColorThemeNonNull.textColor2,
                  ),
                ),
              );
            }),
          ),
        SizedBox(height: 12.h),

        if (current != null &&
            (current.title is String) &&
            (current.title as String).trim().isNotEmpty)
          Text(
            current.title,
            style: context.textTheme.bodyMedium?.copyWith(
              color: context.customColorThemeNonNull.textColor1,
            ),
          ),

        SizedBox(height: 15.h),
      ],
    );
  }

  void _goNextPage(BuildContext context, WidgetRef ref) async {
    final wifiInfo = await _resolveWifiCredentials();
    if (!context.mounted) return;

    if (wifiInfo.ssid == null) {
      Log.i('当前WiFi信息不足，进入WiFi配置页面');
      WifiConfigRoute(
        pid: pid,
        deviceName: "",
        nextRoute: "add_device_progress",
      ).push(context);
      return;
    }

    final ssid = wifiInfo.ssid!;
    final pwd = wifiInfo.password!;
    Log.i(
      '119615 guid 当前线程: ${Isolate.current.debugName ?? Isolate.current.hashCode}',
    );

    Log.i('当前WiFi SSID: $ssid, 已存储密码，直接进入配网进度页面');
    AddDeviceProgressRoute(
      pid: pid,
      ssid: ssid,
      pwd: pwd,
      deviceName: deviceName,
      virtualId: null,
    ).push(context);
  }

  Future<({String? ssid, String? password})> _resolveWifiCredentials() async {
    final ssidResult =
        await WifiUtils.getInstance().getCurrentWifiSsidResult();
    if (!ssidResult.hasPermission) {
      ToastUtil.show("请开启定位权限后再尝试");
      return (ssid: null, password: null);
    }
    final ssid = ssidResult.ssid;
    if (ssid == null) return (ssid: null, password: null);

    final spUnit = await SPUtils.getInstance();
    final pwd = spUnit.getString(ssid);
    if (pwd.isEmpty) {
      return (ssid: null, password: null);
    }

    return (ssid: ssid, password: pwd);
  }

  _goHelpWebPage(BuildContext context, String helpUrl) {
    WebPageRoute(title: "", url: helpUrl).push(context);
  }
}
